package com.chenliang.controller;

import com.chenliang.domain.SysLog;
import com.chenliang.service.ISysLogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;


import javax.servlet.http.HttpServletRequest;
import java.util.Date;


/**
 * @ProjectName: mavenSSM
 * @Package: com.chenliang.controller
 * 作用：
 */
@Component
@Aspect
public class LogAop {

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private ISysLogService sysLogService;

    private Date visitTime;

@Pointcut("execution(* com.chenliang.controller.*.*(..))")
    public void logPointcut(){}


//前置通知，主要是获得开始时间，执行哪个类，执行哪个方法
@Before("logPointcut()")
public void doBefor(JoinPoint jp){
    visitTime=new Date();
}

@After("logPointcut()")
public void doAfter(JoinPoint jp){

    try {
        long time = new Date().getTime();  //获取访问的时长
//获取执行的类名
        String typeName = jp.getSignature().getDeclaringTypeName();
//获取执行的方法名
        String methodname = jp.getSignature().getName();
//    获取访问路径
        String requestURL = request.getRequestURI();
//    获取访问的ip
        String ip = request.getRemoteAddr();
//获取当前操作的用户
        SecurityContext context = SecurityContextHolder.getContext();
        String username = ((User) (context.getAuthentication().getPrincipal())).getUsername();

//将信息封装到对象中
        SysLog sysLog=new SysLog();
        sysLog.setExecutionTime(time);
        sysLog.setIp(ip);
        sysLog.setMethod("[类名]"+typeName+"[方法名]"+methodname);
        sysLog.setUrl(requestURL);
        sysLog.setUsername(username);
        sysLog.setVisitTime(visitTime);
        sysLogService.saveSysLog(sysLog);
    } catch (Exception e) {
        System.out.println("日志信息"+e.getMessage());
    }


}






}